<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>03_计算属性和监视</title>
</head>
<body>

<script type="text/javascript">
  /* 
   需求: 一个人, 有firstName和lastName
   需要给这个添加fullName, 要求如下:
   1. fullName的组成: firstName-lastName
   2. 如果firstName或lastName变化, fullName也要跟着变
   3. 如果fullName改变了, firstName/lastName也要跟着变
   */
  const p = {
    firstName: 'A',
    lastName: 'B'
  }
  // 通过.直接添加
  // p.fullName = p.firstName + '-' + p.lastName
  // console.log(p.fullName)


  Object.defineProperty(p, 'fullName', { // 配置对象 ==> 属性描述符
    // 当读取属性值时调用, 将执行的返回值作为属性值, this是属性所属的对象
    get () { // getter
      console.log('get()')
      return this.firstName + '-' + this.lastName
    },
    // 当设置了新的属性值是调用, 用来监视属性值变化, this是属性所属的对象
    set(value) { // setter
      console.log('set()', value)
      const names = value.split('-')
      this.firstName = names[0]
      this.lastName = names[1]
    } 
  })
  console.log(p.fullName)


  p.firstName = 'C'
  p.lastName = 'D'
  console.log(p.fullName)

  p.fullName = 'E-F'
  console.log(p.firstName, p.lastName)

  console.log(p)
</script>
</body>
</html>